<?php
require('global.php');
ini_set('display_errors', 1);
header('Content-type:text/html;charset=utf-8');
function getErrorMsg($status, $msg)
{
    $code = [];
    $code['status'] = intval($status);
    $code['msg'] = $msg;
    return $code;
}

function changeOrderStatus($order_status)
{
    if ($order_status == '订单结算' || $order_status == '订单付款') {
        $order_status = 1;
    } else if ($order_status == '订单失效') {
        $order_status = 0;
    }
    return $order_status;
}

function getGoodTkRateByNumId($num_iid)
{
    $mysql_server_name = MYSQL_SERVER_NAME; //改成自己的mysql数据库服务器

    $mysql_username = MYSQL_USERNAME; //改成自己的mysql数据库用户名

    $mysql_password = MYSQL_PASSWORD; //改成自己的mysql数据库密码

    $mysql_database = MYSQL_DATABASE; //改成自己的mysql数据库名
    $link = @mysqli_connect($mysql_server_name, $mysql_username, $mysql_password) or die("error connecting"); //连接数据库
    mysqli_select_db($link, MYSQL_DATABASE);
    mysqli_set_charset($link, 'utf8');
    $sql = 'SELECT `vr`.`mp_good`.`tk_rate` FROM `vr`.`mp_good` WHERE `vr`.`mp_good`.`num_iid` =' . $num_iid . '  LIMIT 1';
    $result = mysqli_query($link, $sql);
    //$data=mysqli_fetch_all($result,MYSQLI_ASSOC);
    //$data=mysqli_fetch_array($result);
    $tk_rate = mysqli_fetch_assoc($result);
    if (isset($tk_rate) && $tk_rate != NULL) {
        return $tk_rate['tk_rate'];
    } else {
        return false;
    }
}

function getTimeCondition()
{
    $time = date('Y-m-d', time());
    $time_arr = explode('-', $time);
    $year = $time_arr[0];
    $month = $time_arr[1];
    $day = $time_arr[2];
    if ($month == 1) {
        if ($day <= 20) {
            $day = 1;
            $month = 12;
            $year = $year - 1;
            $time = strtotime($year . '-' . $month . '-' . $day);
            $time = $time - 1;
            return $time;
        } else {
            $day = 1;
            $time = strtotime($year . '-' . $month . '-' . $day);
            $time = $time - 1;
            return $time;
        }
    } else {
        if ($day <= 20) {
            $day = 1;
            $month = $month - 1;
            $time = strtotime($year . '-' . $month . '-' . $day);
            $time = $time - 1;
            return $time;
        } else {
            $day = 1;
            $time = strtotime($year . '-' . $month . '-' . $day);
            $time = $time - 1;
            return $time;
        }
    }
}

function getMemberVipLevelByAdZoneId($ad_zone_id)
{
    $mysql_server_name = MYSQL_SERVER_NAME; //改成自己的mysql数据库服务器

    $mysql_username = MYSQL_USERNAME; //改成自己的mysql数据库用户名

    $mysql_password = MYSQL_PASSWORD; //改成自己的mysql数据库密码

    $mysql_database = MYSQL_DATABASE; //改成自己的mysql数据库名
    $link = @mysqli_connect($mysql_server_name, $mysql_username, $mysql_password) or die("error connecting"); //连接数据库
    mysqli_select_db($link, MYSQL_DATABASE);
    mysqli_set_charset($link, 'utf8');
    $sql = 'SELECT `vr`.`mp_member_vip`.`level` FROM `vr`.`mp_member_vip`, `vr`.`mp_member_vip_level` WHERE `vr`.`mp_member_vip`.`ad_zone_id` = ' . $ad_zone_id . ' AND `vr`.`mp_member_vip`.`level` = `vr`.`mp_member_vip_level`.`level` LIMIT 1';
    $result = mysqli_query($link, $sql);
    //$data=mysqli_fetch_all($result,MYSQLI_ASSOC);
    //$data=mysqli_fetch_array($result);
    return mysqli_fetch_assoc($result);
}

function getOrderInfoByExcel($dataset)
{
    $data = [];
    if ($dataset === false) {
        return false;
    } else {
        $count = count($dataset);
        $j = 0;
        for ($i = 30; $i <= $count - 30; $i++) {
            if ($i % 30 == 0) {
                $data[$j]['add_time'] = strtotime($dataset[$i]);
                $data[$j]['title'] = $dataset[$i + 2];
                $data[$j]['num_iid'] = $dataset[$i + 3];
                $data[$j]['seller_id'] = $dataset[$i + 4];
                $data[$j]['seller_shop'] = $dataset[$i + 5];
                $data[$j]['good_num'] = $dataset[$i + 6];
                $data[$j]['good_price'] = $dataset[$i + 7];
                $data[$j]['status'] = $dataset[$i + 8];
                $data[$j]['order_status'] = changeOrderStatus($dataset[$i + 8]);
                $data[$j]['tb_tk_rate'] = $data[$j]['tk_rate'] = $dataset[$i + 10];
                $tk_rate = getGoodTkRateByNumId($data[$j]['num_iid']);
                if ($tk_rate === false) {
                    $data[$j]['tk_rate'] = $dataset[$i + 10];
                    $data[$j]['good_tk_rate'] = $dataset[$i + 10];
                } else {
                    $data[$j]['tk_rate'] = min((float)$data[$j]['tk_rate'], $tk_rate);
                    $data[$j]['good_tk_rate'] = $tk_rate;
                }
                $data[$j]['divide_rate'] = $dataset[$i + 11];
                $data[$j]['pay_money'] = $dataset[$i + 12];
                $data[$j]['tb_effect_est_income'] = $dataset[$i + 13];
                $data[$j]['est_effect_income'] = round($data[$j]['pay_money'] * $data[$j]['tk_rate'] / 100, 2);
                $data[$j]['balance_money'] = $dataset[$i + 14];
                $data[$j]['tb_est_income'] = $dataset[$i + 15];
                if (intval($data[$j]['balance_money']) == 0 || $data[$j]['balance_money'] == NULL) {
                    $data[$j]['est_income'] = round($data[$j]['pay_money'] * $data[$j]['tk_rate'] / 100, 2);
                } else {
                    $data[$j]['est_income'] = round($data[$j]['balance_money'] * $data[$j]['tk_rate'] / 100, 2);
                }
                $cutoff_time = $data[$j]['cutoff_time'] = intval(strtotime($dataset[$i + 16]));
                $time = getTimeCondition();
                if ($cutoff_time > 0 && $cutoff_time < $time) {
                    $data[$j]['order_status'] = 2;
                }
                $data[$j]['commision_rate'] = $dataset[$i + 17];
                $data[$j]['commision_money'] = $dataset[$i + 18];
                $data[$j]['allowance_rate'] = $dataset[$i + 19];
                $data[$j]['allowance_money'] = $dataset[$i + 20];
                $data[$j]['order_number'] = $dataset[$i + 24];
                $ad_zone_id = $data[$j]['ad_zone_id'] = $dataset[$i + 28];
                $data[$j]['ad_name'] = $dataset[$i + 29];
                $data[$j]['level'] = getMemberVipLevelByAdZoneId($ad_zone_id)['level'];
                $data[$j]['is_true'] = 1;
                $j++;
            }
        }
        return $data;
    }
}

function confirmTimeByExcel($data, $time, $Excel_time)
{
    if ($time == $Excel_time) {
        foreach ($data as $k => $v) {
            $add_time = strtotime(date('Y-m-d', $v['add_time']));
            if ($add_time != $time || $add_time != $Excel_time) {
                return false;
            }
        }
        return true;
    } else {
        return false;
    }
}

function getShareOrderRate($tb_tk_rate, $pay_money, $balance_money)
{
    $mysql_server_name = MYSQL_SERVER_NAME; //改成自己的mysql数据库服务器

    $mysql_username = MYSQL_USERNAME; //改成自己的mysql数据库用户名

    $mysql_password = MYSQL_PASSWORD; //改成自己的mysql数据库密码

    $mysql_database = 'share'; //改成自己的mysql数据库名
    $link = @mysqli_connect($mysql_server_name, $mysql_username, $mysql_password) or die("error connecting"); //连接数据库
    mysqli_select_db($link, 'share');
    mysqli_set_charset($link, 'utf8');
    $y_order = [];
    $sql = 'SELECT * FROM share.`y_rate_setting` WHERE share.`y_rate_setting`.`id` = 1 limit 1';
    $result = mysqli_query($link, $sql);
    $rate = mysqli_fetch_assoc($result);
    $y_order['tk_rate'] = round($rate['rate'] * $tb_tk_rate, 2);
    if (!empty($balance_money)) {
        $y_order['est_income'] = round($balance_money * $y_order['tk_rate'] / 100, 2);
    } else {
        $y_order['est_income'] = round($pay_money * $y_order['tk_rate'] / 100, 2);
    }
    $y_order['est_effect_income'] = round($pay_money * $y_order['tk_rate'] / 100, 2);
    return $y_order;
}

function countSum($fields, $member_id)
{
    $mysql_server_name = MYSQL_SERVER_NAME; //改成自己的mysql数据库服务器

    $mysql_username = MYSQL_USERNAME; //改成自己的mysql数据库用户名

    $mysql_password = MYSQL_PASSWORD; //改成自己的mysql数据库密码

    $mysql_database = MYSQL_DATABASE; //改成自己的mysql数据库名
    $link = @mysqli_connect($mysql_server_name, $mysql_username, $mysql_password) or die("error connecting"); //连接数据库
    mysqli_select_db($link, MYSQL_DATABASE);
    mysqli_set_charset($link, 'utf8');
    $sql = 'SELECT SUM(' . $fields . ') as num FROM mp_member_order where mp_member_order.member_id=' . $member_id . ' and  mp_member_order.order_status<>0';
    $result = mysqli_query($link, $sql);
    return mysqli_fetch_all($result, MYSQLI_ASSOC);
}

function countSums($fields, $member_id, $last_time, $time)
{
    $mysql_server_name = MYSQL_SERVER_NAME; //改成自己的mysql数据库服务器

    $mysql_username = MYSQL_USERNAME; //改成自己的mysql数据库用户名

    $mysql_password = MYSQL_PASSWORD; //改成自己的mysql数据库密码

    $mysql_database = MYSQL_DATABASE; //改成自己的mysql数据库名
    $link = @mysqli_connect($mysql_server_name, $mysql_username, $mysql_password) or die("error connecting"); //连接数据库
    mysqli_select_db($link, 'vr');
    mysqli_set_charset($link, 'utf8');
    $sql = 'SELECT SUM(' . $fields . ') as num FROM mp_member_order where mp_member_order.member_id=' . $member_id . ' and mp_member_order.cutoff_time between \'' . $last_time . '\' and \'' . $time . '\' and  mp_member_order.order_status<>0';
    $result = mysqli_query($link, $sql);
    return mysqli_fetch_all($result, MYSQLI_ASSOC);
}

function getMoneyNum($member_id, $level)
{
    $mysql_server_name = MYSQL_SERVER_NAME; //改成自己的mysql数据库服务器

    $mysql_username = MYSQL_USERNAME; //改成自己的mysql数据库用户名

    $mysql_password = MYSQL_PASSWORD; //改成自己的mysql数据库密码

    $mysql_database = MYSQL_DATABASE; //改成自己的mysql数据库名
    $link = @mysqli_connect($mysql_server_name, $mysql_username, $mysql_password) or die("error connecting"); //连接数据库
    mysqli_select_db($link, MYSQL_DATABASE);
    mysqli_set_charset($link, 'utf8');
    $sql = 'SELECT `vr`.`mp_member_vip_level`.`vip_tk_rate`,`vr`.`mp_member_vip_level`.`fee`,`vr`.`mp_member_vip_level`.`activity_title`,`vr`.`mp_member_vip_level`.`activity_cost`,`vr`.`mp_member_vip_level`.`activity_end_time`,`vr`.`mp_member_vip_level`.`vip_name` FROM `vr`.`mp_member_vip_level` WHERE `vr`.`mp_member_vip_level`.`level` = ' . $level . ' LIMIT 1';
    $result = mysqli_query($link, $sql);
    $level = mysqli_fetch_assoc($result);
    if ($level === false) {
        return false;
    }
    $last_time = LAST_TIME;
    $time = getTimeCondition();
    //$where['cutoff_time']=array('between',array('1451577600',$time));
    $total_money = countSums('est_income', $member_id, $last_time, $time);
    $commision_money = countSum('est_income', $member_id);
    if ($member_id != 2) {
        $total_money = round($total_money[0]['num'] * $level['vip_tk_rate'] * $level['fee'], 2);
        $commision_money = round($commision_money[0]['num'] * $level['vip_tk_rate'] * $level['fee'], 2);
    } else {
        $total_money = $total_money[0]['num'];
        $commision_money = $commision_money[0]['num'];
    }
    $balance_money = array($total_money, $commision_money);
    return $balance_money;
}

function editShareRateSetting($data)
{
    ini_set('display_errors', 1);
    $mysql_server_name = MYSQL_SERVER_NAME; //改成自己的mysql数据库服务器

    $mysql_username = MYSQL_USERNAME; //改成自己的mysql数据库用户名

    $mysql_password = MYSQL_PASSWORD; //改成自己的mysql数据库密码

    $mysql_database = 'share'; //改成自己的mysql数据库名
    $link = @mysqli_connect($mysql_server_name, $mysql_username, $mysql_password) or die("error connecting"); //连接数据库
    mysqli_select_db($link, 'share');
    mysqli_set_charset($link, 'utf8');
    $y_order = [];
    $sql = 'SELECT * FROM share.`y_rate_setting` WHERE share.`y_rate_setting`.`id` = 1 limit 1';
    $result = mysqli_query($link, $sql);
    $rate = mysqli_fetch_assoc($result);
    if (!empty($data['balance_money'])) {
        $money = $data['balance_money'];
    } else {
        $money = $data['pay_money'];
    }
    $y_order['rate'] = round($rate['vip_tk_rate'] * $rate['fee'] * $rate['rate'] * $data['tb_tk_rate'], 2);
    $y_order['point'] = $money * $y_order['rate'];
    if ($data['status'] == '订单失效') {
        $y_order['status'] = 0;
    } else if ($data['status'] == '订单付款') {
        $y_order['status'] = 1;
    } else if ($data['status'] == '订单结算') {
        $y_order['status'] = 2;
    }
    $y_order['order'] = $data['order_number'];
    $curlPost = 'order=' . $y_order['order'] . '&status=' . $y_order['status'] . '&point=' . $y_order['point'] . '&rate=' . $y_order['rate'] . '&key=e5a5a5JbIKttTfdbwiG5VqtnxUHfdzqErwhhnGG2qhP3XROjjIf8osGD65IVtCVXY';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://www.zhuang888.com/api/?con=order&act=addOrder');
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($ch);
    curl_close($ch);
    $result = (array)json_decode($data);
    if ($result['code'] == 200 || $result['code'] == 203) {
        return true;
    } else {
        return false;
    }
}

function insertMemberOrderExcel($data, $number)
{    
    $mysql_server_name = MYSQL_SERVER_NAME; //改成自己的mysql数据库服务器

    $mysql_username = MYSQL_USERNAME; //改成自己的mysql数据库用户名

    $mysql_password = MYSQL_PASSWORD; //改成自己的mysql数据库密码

    $mysql_database = MYSQL_DATABASE; //改成自己的mysql数据库名
    $link = @mysqli_connect($mysql_server_name, $mysql_username, $mysql_password) or die("error connecting"); //连接数据库
    mysqli_select_db($link, MYSQL_DATABASE);
    mysqli_set_charset($link, 'utf8');
    for ($i = 0; $i <= $number - 1; $i++) {
    	$datas=[];
    	$data['add_time'] = '';
    	$data['title'] ='';
    	$data['num_iid'] ='';
    	$data['seller_id'] = '';
    	$data['seller_shop'] ='';
    	$data['good_num'] =0;
    	$data['good_price'] = 0;
    	$data['status'] ='';
    	$data['order_status'] = 0;
    	$data['tb_tk_rate'] = 0;
    	$data['tk_rate'] = 0;
    	$data['good_tk_rate'] = 0;
    	$data['divide_rate'] =0;
    	$data['pay_money'] =0;
    	$data['tb_effect_est_income'] = 0;
    	$data['est_effect_income'] = 0;
    	$data['balance_money'] = 0;
    	$data['tb_est_income'] = 0;
    	$data['est_income'] =0;
        $data['cutoff_time'] = '';
    	$data['commision_rate'] = 0;
    	$data['commision_money'] = 0;
    	$data['allowance_rate'] = 0;
    	$data['allowance_money'] = 0;
    	$data['order_number'] = '';
    	$data['ad_zone_id'] = '';
    	$data['ad_name'] ='';
    	$data['level'] = 0;
    	$data['is_true'] = 0;
        $datas = $data[$i];
        $datas['sort'] = $i;
        $sql = 'INSERT INTO `vr`.`mp_member_order`(`vr`.`mp_member_order`.`num_iid`,`vr`.`mp_member_order`.`seller_id`,`vr`.`mp_member_order`.`seller_shop`,`vr`.`mp_member_order`.`good_num`,`vr`.`mp_member_order`.`good_price`,`vr`.`mp_member_order`.`tk_rate`,`vr`.`mp_member_order`.`divide_rate`,`vr`.`mp_member_order`.`pay_money`,`vr`.`mp_member_order`.`balance_money`,`vr`.`mp_member_order`.`cutoff_time`,`vr`.`mp_member_order`.`order_number`,`vr`.`mp_member_order`.`add_time`,`vr`.`mp_member_order`.`ad_zone_id`,`vr`.`mp_member_order`.`ad_name`,`vr`.`mp_member_order`.`order_status`,`vr`.`mp_member_order`.`est_effect_income`,`vr`.`mp_member_order`.`est_income`,`vr`.`mp_member_order`.`commision_money`,`vr`.`mp_member_order`.`allowance_money`,`vr`.`mp_member_order`.`allowance_rate`,`vr`.`mp_member_order`.`commision_rate`,`vr`.`mp_member_order`.`status`,`vr`.`mp_member_order`.`sort`,`vr`.`mp_member_order`.`level`,`vr`.`mp_member_order`.`title`,`vr`.`mp_member_order`.`is_true`,`vr`.`mp_member_order`.`tb_tk_rate`,`vr`.`mp_member_order`.`good_tk_rate`,`vr`.`mp_member_order`.`tb_est_income`,`vr`.`mp_member_order`.`tb_effect_est_income`) VALUES(\'' . $datas['num_iid'] . '\',\'' . $datas['seller_id'] . '\',\'' . $datas['seller_shop'] . '\',' . $datas['good_num'] . ',' . $datas['good_price'] . ',\'' . $datas['tk_rate'] . '\',\'' . $datas['divide_rate'] . '\',' . $datas['pay_money'] . ',' . $datas['balance_money'] . ',\'' . $datas['cutoff_time'] . '\',\'' . $datas['order_number'] . '\',\'' . $datas['add_time'] . '\',\'' . $datas['ad_zone_id'] . '\',\'' . $datas['ad_name'] . '\',\'' . $datas['order_status'] . '\',' . $datas['est_effect_income'] . ',' . $datas['est_income'] . ',' . $datas['commision_money'] . ',' . $datas['allowance_money'] . ',\'' . $datas['allowance_rate'] . '\',\'' . $datas['commision_rate'] . '\',\'' . $datas['status'] . '\',' . $datas['sort'] . ',\'' . $datas['level'] . '\',\'' . $datas['title'] . '\',' . $datas['is_true'] . ',\'' . $datas['tb_tk_rate'] . '\',\'' . $datas['good_tk_rate'] . '\',' . $datas['tb_est_income'] . ',' . $datas['tb_effect_est_income'] . ')';
        $result = mysqli_query($link, $sql);
        $id = mysqli_insert_id($link);
        $res = $id > 0 ? $id : @mysql_result(mysqli_query($link, "SELECT last_insert_id()"), 0);
        if ($res === false || $id == 0) {
            return false;
        }
        $sql = 'SELECT `vr`.`mp_member`.`member_id` FROM `vr`.`mp_member_order`, `vr`.`mp_member` WHERE `vr`.`mp_member_order`.`ad_zone_id` = `vr`.`mp_member`.`ad_zone_id` AND `vr`.`mp_member_order`.`id` =' . $res . ' LIMIT 1';
        $result = mysqli_query($link, $sql);
        $member_id = mysqli_fetch_assoc($result);
        if ($member_id['member_id'] == 2) {
            $share_order = getShareOrderRate($datas['tb_tk_rate'], $datas['pay_money'], $datas['balance_money']);
            $share_order['is_y_order'] = 1;
            $sql = 'UPDATE `vr`.`mp_member_order` SET `vr`.`mp_member_order`.`tk_rate`=' . $share_order['tk_rate'] . ',`vr`.`mp_member_order`.`est_effect_income`=' . $share_order['est_effect_income'] . ',`vr`.`mp_member_order`.`est_income`=' . $share_order['est_income'] . ',`vr`.`mp_member_order`.`is_y_order`=' . $share_order['is_y_order'] . ' WHERE `vr`.`mp_member_order`.`id` = ' . $res;
            $result = mysqli_query($link, $sql);
            $is_y_order = mysqli_affected_rows($link);
            if ($is_y_order === false) {
                return false;
            }
        }
        $sql = 'UPDATE `vr`.`mp_member_order` SET `vr`.`mp_member_order`.`member_id`=' . $member_id['member_id'] . ' WHERE `vr`.`mp_member_order`.`id` = ' . $res;
        $result = mysqli_query($link, $sql);
        $update_member = mysqli_affected_rows($link);
        if ($update_member === false) {
            return false;
        }
        if (intval($datas['level']) >= 1) {
            $member_vip_money = getMoneyNum($member_id['member_id'], $datas['level']);
            if ($member_vip_money === false) {
                return false;
            }
            $sql = 'SELECT `vr`.`mp_member_vip`.`total`,`vr`.`mp_member_vip`.`used`,`vr`.`mp_member_vip`.`freeze`,`vr`.`mp_member_vip`.`est_income` FROM `vr`.`mp_member_vip` WHERE `vr`.`mp_member_vip`.`member_id` = ' . $member_id['member_id'] . ' AND `vr`.`mp_member_vip`.`status` = 1 LIMIT 1';
            $result = mysqli_query($link, $sql);
            $money = mysqli_fetch_assoc($result);
            if ($money['total'] != $member_vip_money[0] || $money['est_income'] != $member_vip_money[1]) {
                $balance_money = $member_vip_money[0] - $money['used'] - $money['freeze'];
                $time = time();
                $sql = 'UPDATE `vr`.`mp_member_vip` SET `vr`.`mp_member_vip`.`total`=' . $member_vip_money[0] . ',`vr`.`mp_member_vip`.`est_income`=' . $member_vip_money[1] . ',`vr`.`mp_member_vip`.`balance`=' . $balance_money . ',`vr`.`mp_member_vip`.`update_time`=' . $time . ' WHERE `vr`.`mp_member_vip`.`member_id` = ' . $member_id['member_id'] . ' AND `vr`.`mp_member_vip`.`status` = 1';
                $result = mysqli_query($link, $sql);
                $update_money = mysqli_affected_rows($link);
                if ($update_money === false) {
                    return false;
                }
            }
        }
        if ($member_id['member_id'] == 2) {
            $y_order = editShareRateSetting($datas);
            if ($y_order == false) {
                return false;
            }
        }
    }
    return true;
}

function updateMemberOrderExcel($data, $number)
{
    $mysql_server_name = MYSQL_SERVER_NAME; //改成自己的mysql数据库服务器

    $mysql_username = MYSQL_USERNAME; //改成自己的mysql数据库用户名

    $mysql_password = MYSQL_PASSWORD; //改成自己的mysql数据库密码

    $mysql_database = MYSQL_DATABASE; //改成自己的mysql数据库名
    $link = @mysqli_connect($mysql_server_name, $mysql_username, $mysql_password) or die("error connecting"); //连接数据库
    mysqli_select_db($link, MYSQL_DATABASE);
    mysqli_set_charset($link, 'utf8');
    for ($i = 0; $i <= $number - 1; $i++) {
        $order_number = $data[$i]['order_number'];
        $sql = 'SELECT `vr`.`mp_member_order`.`id`,`vr`.`mp_member_order`.`member_id`,`vr`.`mp_member_order`.`order_status`,`vr`.`mp_member_order`.`level`,`vr`.`mp_member_order`.`tk_rate`,`vr`.`mp_member_order`.`tb_tk_rate`,`vr`.`mp_member_order`.`good_tk_rate` FROM `vr`.`mp_member_order` WHERE `vr`.`mp_member_order`.`order_number` = ' . $order_number . ' AND `vr`.`mp_member_order`.`sort` = ' . $i . ' LIMIT 1';
        $result = mysqli_query($link, $sql);
        $result = mysqli_fetch_assoc($result);
        $sql = 'SELECT `vr`.`mp_member`.`member_id` FROM `vr`.`mp_member_order`, `vr`.`mp_member` WHERE `vr`.`mp_member_order`.`ad_zone_id` = `vr`.`mp_member`.`ad_zone_id` AND `vr`.`mp_member_order`.`id` =' . $result['id'] . ' LIMIT 1';
        $member = mysqli_query($link, $sql);
        $member_id = mysqli_fetch_assoc($member);
        if ($member_id['member_id'] != 0) {
            $result['member_id'] = $member_id['member_id'];
            $data[$i]['member_id'] = $member_id['member_id'];
        }
        if (isset($result) && $result != NULL) {
            $datas = $data[$i];
            if (intval($result['good_tk_rate']) != 0) {
                $datas['good_tk_rate'] = $result['good_tk_rate'];
            } else {
                $result['good_tk_rate'] = $datas['good_tk_rate'];
            }
            if (intval($result['level']) > 0) {
                $datas['level'] = intval($result['level']);
            }
            if ($result['tk_rate'] != trim($datas['tk_rate'], '%')) {
                if ($result['tb_tk_rate'] > trim($datas['tb_tk_rate'], '%')) {
                    $datas['tk_rate'] = min($datas['tb_tk_rate'], $result['good_tk_rate']);
                } else {
                    if (intval($result['tb_tk_rate']) > 0) {
                        $datas['tk_rate'] = min($result['tb_tk_rate'], $result['good_tk_rate']);
                        $datas['tb_tk_rate'] = $result['tb_tk_rate'];
                    } else {
                        $datas['tk_rate'] = min($datas['tb_tk_rate'], $result['good_tk_rate']);
                    }
                }
                $datas['est_effect_income'] = round($datas['pay_money'] * $datas['tk_rate'] / 100, 2);
                if (intval($datas['balance_money']) == 0 || $datas['balance_money'] == NULL) {
                    $datas['est_income'] = round($datas['pay_money'] * $datas['tk_rate'] / 100, 2);
                } else {
                    $datas['est_income'] = round($datas['balance_money'] * $datas['tk_rate'] / 100, 2);
                }
            }
            $datas['update_time'] = time();
            if ($member_id['member_id'] == 2) {
                $share_order = getShareOrderRate($datas['tb_tk_rate'], $datas['pay_money'], $datas['balance_money']);
                $datas['is_y_order'] = 1;
                $datas['tk_rate'] = $share_order['tk_rate'];
                $datas['est_income'] = $share_order['est_income'];
                $datas['est_effect_income'] = $share_order['est_effect_income'];
                $sql = 'UPDATE `vr`.`mp_member_order` SET `vr`.`mp_member_order`.`num_iid`=\'' . $datas['num_iid'] . '\',`vr`.`mp_member_order`.`seller_id`=\'' . $datas['seller_id'] . '\',`vr`.`mp_member_order`.`seller_shop`=\'' . $datas['seller_shop'] . '\',`vr`.`mp_member_order`.`good_num`=\'' . $datas['good_num'] . '\',`vr`.`mp_member_order`.`good_price`=\'' . $datas['good_price'] . '\',`vr`.`mp_member_order`.`tk_rate`=\'' . $datas['tk_rate'] . '\',`vr`.`mp_member_order`.`divide_rate`=\'' . $datas['divide_rate'] . '\',`vr`.`mp_member_order`.`pay_money`=\'' . $datas['pay_money'] . '\',`vr`.`mp_member_order`.`balance_money`=\'' . $datas['balance_money'] . '\',`vr`.`mp_member_order`.`cutoff_time`=\'' . $datas['cutoff_time'] . '\',`vr`.`mp_member_order`.`order_number`=\'' . $datas['order_number'] . '\',`vr`.`mp_member_order`.`add_time`=\'' . $datas['add_time'] . '\',`vr`.`mp_member_order`.`ad_zone_id`=\'' . $datas['ad_zone_id'] . '\',`vr`.`mp_member_order`.`ad_name`=\'' . $datas['ad_name'] . '\',`vr`.`mp_member_order`.`order_status`=\'' . $datas['order_status'] . '\',`vr`.`mp_member_order`.`est_effect_income`=\'' . $datas['est_effect_income'] . '\',`vr`.`mp_member_order`.`est_income`=\'' . $datas['est_income'] . '\',`vr`.`mp_member_order`.`commision_money`=\'' . $datas['commision_money'] . '\',`vr`.`mp_member_order`.`allowance_money`=\'' . $datas['allowance_money'] . '\',`vr`.`mp_member_order`.`allowance_rate`=\'' . $datas['allowance_rate'] . '\',`vr`.`mp_member_order`.`commision_rate`=\'' . $datas['commision_rate'] . '\',`vr`.`mp_member_order`.`status`=\'' . $datas['status'] . '\',`vr`.`mp_member_order`.`update_time`=\'' . $datas['update_time'] . '\',`vr`.`mp_member_order`.`level`=\'' . $datas['level'] . '\',`vr`.`mp_member_order`.`title`=\'' . $datas['title'] . '\',`vr`.`mp_member_order`.`is_true`=\'' . $datas['is_true'] . '\',`vr`.`mp_member_order`.`tb_tk_rate`=\'' . $datas['tb_tk_rate'] . '\',`vr`.`mp_member_order`.`good_tk_rate`=\'' . $datas['good_tk_rate'] . '\',`vr`.`mp_member_order`.`tb_est_income`=\'' . $datas['tb_est_income'] . '\',`vr`.`mp_member_order`.`tb_effect_est_income`=\'' . $datas['tb_effect_est_income'] . '\',`vr`.`mp_member_order`.`is_y_order`=\'' . $datas['is_y_order'] . '\' WHERE `vr`.`mp_member_order`.`id` = ' . $result['id'];
                $results = mysqli_query($link, $sql);
                $res = mysqli_affected_rows($link);
            } else {
                $sql = 'UPDATE `vr`.`mp_member_order` SET `vr`.`mp_member_order`.`num_iid`=\'' . $datas['num_iid'] . '\',`vr`.`mp_member_order`.`seller_id`=\'' . $datas['seller_id'] . '\',`vr`.`mp_member_order`.`seller_shop`=\'' . $datas['seller_shop'] . '\',`vr`.`mp_member_order`.`good_num`=\'' . $datas['good_num'] . '\',`vr`.`mp_member_order`.`good_price`=\'' . $datas['good_price'] . '\',`vr`.`mp_member_order`.`tk_rate`=\'' . $datas['tk_rate'] . '\',`vr`.`mp_member_order`.`divide_rate`=\'' . $datas['divide_rate'] . '\',`vr`.`mp_member_order`.`pay_money`=\'' . $datas['pay_money'] . '\',`vr`.`mp_member_order`.`balance_money`=\'' . $datas['balance_money'] . '\',`vr`.`mp_member_order`.`cutoff_time`=\'' . $datas['cutoff_time'] . '\',`vr`.`mp_member_order`.`order_number`=\'' . $datas['order_number'] . '\',`vr`.`mp_member_order`.`add_time`=\'' . $datas['add_time'] . '\',`vr`.`mp_member_order`.`ad_zone_id`=\'' . $datas['ad_zone_id'] . '\',`vr`.`mp_member_order`.`ad_name`=\'' . $datas['ad_name'] . '\',`vr`.`mp_member_order`.`order_status`=\'' . $datas['order_status'] . '\',`vr`.`mp_member_order`.`est_effect_income`=\'' . $datas['est_effect_income'] . '\',`vr`.`mp_member_order`.`est_income`=\'' . $datas['est_income'] . '\',`vr`.`mp_member_order`.`commision_money`=\'' . $datas['commision_money'] . '\',`vr`.`mp_member_order`.`allowance_money`=\'' . $datas['allowance_money'] . '\',`vr`.`mp_member_order`.`allowance_rate`=\'' . $datas['allowance_rate'] . '\',`vr`.`mp_member_order`.`commision_rate`=\'' . $datas['commision_rate'] . '\',`vr`.`mp_member_order`.`status`=\'' . $datas['status'] . '\',`vr`.`mp_member_order`.`update_time`=\'' . $datas['update_time'] . '\',`vr`.`mp_member_order`.`level`=\'' . $datas['level'] . '\',`vr`.`mp_member_order`.`title`=\'' . $datas['title'] . '\',`vr`.`mp_member_order`.`is_true`=\'' . $datas['is_true'] . '\',`vr`.`mp_member_order`.`tb_tk_rate`=\'' . $datas['tb_tk_rate'] . '\',`vr`.`mp_member_order`.`good_tk_rate`=\'' . $datas['good_tk_rate'] . '\',`vr`.`mp_member_order`.`tb_est_income`=\'' . $datas['tb_est_income'] . '\',`vr`.`mp_member_order`.`tb_effect_est_income`=\'' . $datas['tb_effect_est_income'] . '\' WHERE `vr`.`mp_member_order`.`id` = ' . $result['id'];
                $results = mysqli_query($link, $sql);
                $res = mysqli_affected_rows($link);
            }
            if ($res === false) {
                return false;
            }
            if (intval($datas['level']) >= 1) {
                $member_vip_money = getMoneyNum($result['member_id'], $datas['level']);
                if ($member_vip_money === false) {
                    return false;
                }
                $sql = 'SELECT `vr`.`mp_member_vip`.`total`,`vr`.`mp_member_vip`.`used`,`vr`.`mp_member_vip`.`freeze`,`vr`.`mp_member_vip`.`est_income` FROM `vr`.`mp_member_vip` WHERE `vr`.`mp_member_vip`.`member_id` = ' . $member_id['member_id'] . ' AND `vr`.`mp_member_vip`.`status` = 1 LIMIT 1';
                $results = mysqli_query($link, $sql);
                $money = mysqli_fetch_assoc($results);
                if ($money['total'] != $member_vip_money[0] || $money['est_income'] != $member_vip_money[1]) {
                    $balance_money = $member_vip_money[0] - $money['used'] - $money['freeze'];
                    $time = time();
                    $sql = 'UPDATE `vr`.`mp_member_vip` SET `vr`.`mp_member_vip`.`total`=' . $member_vip_money[0] . ',`vr`.`mp_member_vip`.`est_income`=' . $member_vip_money[1] . ',`vr`.`mp_member_vip`.`balance`=' . $balance_money . ',`vr`.`mp_member_vip`.`update_time`=' . $time . ' WHERE `vr`.`mp_member_vip`.`member_id` = ' . $member_id['member_id'] . ' AND `vr`.`mp_member_vip`.`status` = 1';
                    $results = mysqli_query($link, $sql);
                    $update_money = mysqli_affected_rows($link);
                    if ($update_money === false) {
                        return false;
                    }
                }
            }
        }
        if ($member_id['member_id'] == 2) {
            $y_order = editShareRateSetting($datas);
            if ($y_order == false) {
                return false;
            }
        }
    }
    return true;
}

function addExcelInfo($data, $time, $path)
{
    $mysql_server_name = MYSQL_SERVER_NAME; //改成自己的mysql数据库服务器

    $mysql_username = MYSQL_USERNAME; //改成自己的mysql数据库用户名

    $mysql_password = MYSQL_PASSWORD; //改成自己的mysql数据库密码

    $mysql_database = MYSQL_DATABASE; //改成自己的mysql数据库名
    $link = @mysqli_connect($mysql_server_name, $mysql_username, $mysql_password) or die("error connecting"); //连接数据库
    mysqli_select_db($link, MYSQL_DATABASE);
    mysqli_set_charset($link, 'utf8');
    mysqli_query($link, "START TRANSACTION");
    if ($data == false) {
        return getErrorMsg(0, '获取excel数据为false 文件:' . $path);
    } else {
        $number = count($data);
        $Excel_time = strtotime(date('Y-m-d', $data[0]['add_time']));
        $time_msg = confirmTimeByExcel($data, $time, $Excel_time);
        if ($time_msg === false) {
            mysqli_rollback($link);
            return getErrorMsg(0, 'excel数据日期不正确 文件:' . $path);
        }
        $times = $time + 86399;
        $sql = 'SELECT * FROM `vr`.`mp_member_order` WHERE ( `vr`.`mp_member_order`.`add_time` BETWEEN \'' . $time . '\' AND \'' . $times . '\' ) AND `vr`.`mp_member_order`.`is_edit` = 0';
        $result = mysqli_query($link, $sql);
        $res = mysqli_fetch_all($result, MYSQLI_ASSOC);
        if ($time == $Excel_time) {
            if (isset($res) && $res != NULL) {
                if (count($res) != $number) {
                    $sql = 'DELETE FROM `vr`.`mp_member_order` WHERE ( `vr`.`mp_member_order`.`add_time` BETWEEN \'' . $time . '\' AND \'' . $times . '\' ) AND `vr`.`mp_member_order`.`is_edit` = 0';
                    $result = mysqli_query($link, $sql);
                    $res = mysqli_affected_rows($link);
                    if ($res === false) {
                        mysqli_rollback($link);
                        return getErrorMsg(0, '删除订单出错 文件:' . $path);
                    } else {
                        mysqli_commit($link);
                    }
                    mysqli_query($link, "START TRANSACTION");
                    $member_order = insertMemberOrderExcel($data, $number);
                    if ($member_order === false) {
                        mysqli_rollback($link);
                        return getErrorMsg(0, '更新导入订单出错 文件:' . $path);
                    }
                } else {
                    $member_order = updateMemberOrderExcel($data, $number);
                    if ($member_order === false) {
                        mysqli_rollback($link);
                        return getErrorMsg(0, '更新订单出错 文件:' . $path);
                    }
                }
            } else {
                $member_order = insertMemberOrderExcel($data, $number);
                if ($member_order === false) {
                    mysqli_rollback($link);
                    return getErrorMsg(0, '导入订单出错 文件:' . $path);
                }
            }
        } else {
            mysqli_rollback($link);
            return getErrorMsg(0, '订单时间不一致 文件:' . $path);
        }
        mysqli_commit($link);
        return getErrorMsg(1, '上传成功 文件:' . $path);
    }
}

function readExcel($file_path, $page)
{
    error_reporting(E_ALL);
    date_default_timezone_set('Asia/ShangHai');

    /** PHPExcel_IOFactory */
    include_once './phpExcel/Classes/PHPExcel/IOFactory.php';


    // Check prerequisites
    if (!file_exists($file_path)) {
        exit("not found");
    }

    $reader = PHPExcel_IOFactory::createReader('Excel5'); //设置以Excel5格式(Excel97-2003工作簿)
    $PHPExcel = $reader->load($file_path); // 载入excel文件
    $sheet = $PHPExcel->getSheet($page); // 读取第一個工作表
    $highestRow = $sheet->getHighestRow(); // 取得总行数
    $highestColumm = $sheet->getHighestColumn(); // 取得总列数
    $highestColumm = PHPExcel_Cell::columnIndexFromString($highestColumm);
    if ($highestColumm != 30) {
        return false;
    } else {
        /** 循环读取每个单元格的数据 */
        for ($row = 1; $row <= $highestRow; $row++) {//行数是以第1行开始
            for ($column = 'A'; PHPExcel_Cell::columnIndexFromString($column) <= $highestColumm; $column++) {//列数是以A列开始
                $dataset[] = $sheet->getCell($column . $row)->getValue();
                // echo $column.$row.":".$sheet->getCell($column.$row)->getValue()."<br />";
            }
        }
        //$dataset=mb_convert_encoding(var_export($dataset,true),"gb2312","utf-8");
        return $dataset;
    }
}

function my_scandir($path, $order)
{
    $files = [];
    $msg = '';
    if (is_dir($path)) {
        if ($dir = opendir($path)) {
            while (($file = readdir($dir)) !== false) {
                if ($file != "." && $file != "..") {
                    if (is_dir($path . "/" . $file)) {
                        $files[$file] = my_scandir($path . "/" . $file, $order);
                    } else {
                        $files[] = $path . "/" . $file;
                        $data = readExcel($path . "/" . $file, 0);
                        $time = strtotime(str_replace($order . '/', "", $path));
                        $data = getOrderInfoByExcel($data);
                        if (!empty($data)) {
                            $res = addExcelInfo($data, $time, $path . "/" . $file);
                            echo $res['msg']."\n\r";
                        } else {
                            echo '上传成功 文件:' . $path . "/" . $file."\n\r";
                        }
                    }
                }
            }
            closedir($dir);
        }
    }
}

$path = '/usr/local/apache2/htdocs/vr_crm/data/upload/order';
$t=isset($_GET['t'])?intval($_GET['t']):3;
$y='';
$m='';
$d='';
$file=[];
$y=explode('-',date('Y-m-d',time()))[0];
$m=explode('-',date('Y-m-d',time()))[1];
$d=explode('-',date('Y-m-d',time()))[2];
$file_name=[];
if($t==0){
  if($d>20){
      if($m==1){
         $file_name[]=$path."/".$y."/".$m;
         $file_name[]=$path."/".($y-1)."/12";
      }else{
         $file_name[]=$path."/".$y."/".$m;
         $file_name[]=$path."/".$y."/0".($m-1);
      }
  }else{
         $file_name[]=$path."/".$y."/".$m;
  }
}else{
  if($d>20){
      if($m==1){
        for ($i=0; $i <$t ; $i++) { 
          $yt=0;
          $mt=0;
          $dt=0;
          $yt=explode('-',date('Y-m-d',time()-$i*86400))[0];
          $mt=explode('-',date('Y-m-d',time()-$i*86400))[1];
          $dt=explode('-',date('Y-m-d',time()-$i*86400))[2];
          $file_name[]=$path."/".$yt."/".$mt."/".$dt;
        }
         $file_name[]=$path."/".($y-1)."/12";
      }else{
        for ($i=0; $i <$t ; $i++) { 
          $yt=0;
          $mt=0;
          $dt=0;
          $yt=explode('-',date('Y-m-d',time()-$i*86400))[0];
          $mt=explode('-',date('Y-m-d',time()-$i*86400))[1];
          $dt=explode('-',date('Y-m-d',time()-$i*86400))[2];
          $file_name[]=$path."/".$yt."/".$mt."/".$dt;
        }
         $file_name[]=$path."/".$y."/0".($m-1);
      }
  }else{
      for ($i=0; $i <$t ; $i++) { 
        $yt=0;
        $mt=0;
        $dt=0;
        $yt=explode('-',date('Y-m-d',time()-$i*86400))[0];
        $mt=explode('-',date('Y-m-d',time()-$i*86400))[1];
        $dt=explode('-',date('Y-m-d',time()-$i*86400))[2];
        $file_name[]=$path."/".$yt."/".$mt."/".$dt;
      }
  }
}
foreach ($file_name as $k => $v) {
    $res = my_scandir($v, $path);
}  

